package ui;

import action.showordSetting;
import cn.hutool.core.io.FileUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.MultiLineLabelUI;
import compontent.StorageComponent;
import constant.Constant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.*;


public class SettingDialog extends DialogWrapper {
    /**
     * 项目
     */
    private Project project;

    /**
     * 窗内文字
     */
    private String modelText, timeText;

    /**
     * 备选值
     */
    private String[] modelSelectedValues;

    /**
     * 时间备选值
     */
    private String[] timeSelectedValues, wordsSelectedValues,pageSelectedValues;

    /**
     * 默认选中模型
     */
    private String defaultModelValue;

    /**
     * 默认选中时间
     */
    private String defaultTimeValue, defaultWordValue,defaultPageValue;

    /**
     * 参数校验器
     */
    private InputValidator timeFor,wordNum,page;

    /**
     * 模型和时间选择框
     */
    private ComboBox<String> timeSelector, modelSelector, wordSelector,pageSelector;

    public SettingDialog(@Nullable Project project, String title, String timeText
            , String[] timeSelectedValues
            , InputValidator timeFor, String[] wordsSelectedValues, InputValidator wordNum,String[] pageSelectedValues, InputValidator pageNum) {
        super(project);
        setTitle(title);
        this.timeText = timeText;
        this.timeSelectedValues = isEmpty(timeSelectedValues) ? initTimeSelectValues() : timeSelectedValues;
        this.wordsSelectedValues = isEmpty(wordsSelectedValues) ? initWordSelectValues() : wordsSelectedValues;
        this.pageSelectedValues = isEmpty(pageSelectedValues) ? initPageSelectValues() : pageSelectedValues;

        this.defaultModelValue = readFromStorage("lastSelectedMinutes");
        this.defaultTimeValue = readFromStorage("lastSelectedMinutes");
        this.defaultWordValue = readFromStorage("lastSelectedWordNum");
        this.defaultPageValue = readFromStorage("lastSelectedPage");

        this.timeFor = timeFor;
        this.wordNum = wordNum;
        this.page = wordNum;

        StorageComponent.save("wordIndex", "0");

        this.init();
    }

    public SettingDialog setProject(Project project) {
        this.project = project;
        return this;
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel panel = new JPanel();
        panel.setMinimumSize(new Dimension(245,200));
        panel.setPreferredSize(new Dimension(300,200));
        panel.setLayout(new FlowLayout(FlowLayout.LEFT));

        //时间选择panel
        JPanel timeSelectorPanel = this.createMessagePanel(this.timeText);
        timeSelector = new ComboBox<>(220);
        timeSelector.setEditable(true);
        timeSelector.setModel(new DefaultComboBoxModel<>(timeSelectedValues));
        timeSelector.getEditor().setItem(this.defaultTimeValue);
        timeSelector.setSelectedItem(this.defaultTimeValue);
        timeSelectorPanel.add(timeSelector);


        //单词数量选择panel
        JPanel wordSelectorPanel = this.createWordMessagePanel(Constant.Settings.SETTING_WORD_SELECTOR_TEXT);
        wordSelector = new ComboBox<>(220);
        wordSelector.setEditable(true);
        wordSelector.setModel(new DefaultComboBoxModel<>(wordsSelectedValues));
        wordSelector.getEditor().setItem(this.defaultWordValue);
        wordSelector.setSelectedItem(this.defaultWordValue);
        wordSelectorPanel.add(wordSelector);



        //页数选择panel
        JPanel pageSelectorPanel = this.createWordMessagePanel(Constant.Settings.SETTING_WORD_PAGE_SELECTOR_TEXT);
        pageSelector = new ComboBox<>(220);
        pageSelector.setEditable(true);
        pageSelector.setModel(new DefaultComboBoxModel<>(pageSelectedValues));
        pageSelector.getEditor().setItem(this.defaultPageValue);
        pageSelector.setSelectedItem(this.defaultPageValue);
        pageSelectorPanel.add(pageSelector);


        panel.add(timeSelectorPanel);
        panel.add(wordSelectorPanel);
        panel.add(pageSelectorPanel);


        panel.setVisible(true);
        return panel;
    }

    /**
     * 创建一个带有图标的panel
     *
     * @return 图标panel
     */
    @NotNull
    protected JPanel createIconPanel() {
        JPanel panel = new JPanel(new BorderLayout(15, 0));
//        Container container = new Container();
//        container.setLayout(new BorderLayout());
//        panel.add(container, "West");

        return panel;
    }

    @NotNull
    protected JPanel createMessagePanel(String text) {
        JPanel messagePanel = new JPanel(new BorderLayout());
        JLabel textLabel = new JLabel(text);
        textLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
        textLabel.setUI(new MultiLineLabelUI());
        messagePanel.add(textLabel, "North");
        return messagePanel;
    }

    @NotNull
    protected JPanel createWordMessagePanel(String text) {
        JPanel wordPanel = new JPanel(new BorderLayout());
        JLabel wordLabel = new JLabel(text);
        wordLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
        wordLabel.setUI(new MultiLineLabelUI());
        wordPanel.add(wordLabel, "North");
        return wordPanel;
    }

    /**
     * 获得选择的时间
     *
     * @return 提醒时间
     */
    private String getTimeSelectorValue() {
        Object o = this.timeSelector.getSelectedItem();
        return o != null ? o.toString() : "";
    }

    /**
     * 获得选择的单词数
     *
     * @return 提醒时间
     */
    private String getWordSelectorValue() {
        Object o = this.wordSelector.getSelectedItem();
        return o != null ? o.toString() : "";
    }
    private String getPageSelectorValue() {
        Object o = this.pageSelector.getSelectedItem();
        return o != null ? o.toString() : "";
    }


    /**
     * 创建设置窗口
     *
     * @return 点击 “ok” 按钮后返回所选中的值
     */
    public String createSettingDialog() {
        this.show();
        String time = getTimeSelectorValue();
        String word = getWordSelectorValue();
        String page = getPageSelectorValue();
        saveToStorage(time);
        saveWordToStorage(word);
        savePageToStorage(page);
        return time + "-" + word + "-" + page;
    }

    /**
     * 从存储中读取
     *
     * @param key 是否是读取模型
     * @return 存储的值或默认生成备选的第一项的值
     */
    public String readFromStorage(String key) {
        if ("lastSelectedMinutes".equals(key)) {
            return StorageComponent.getValue(key) == null
                    ? isEmpty(timeSelectedValues) ? "" : timeSelectedValues[0]
                    : StorageComponent.getValue("lastSelectedMinutes");
        } else if ("lastSelectedWordNum".equals(key)){
            return StorageComponent.getValue(key) == null
                    ? isEmpty(wordsSelectedValues) ? "" : wordsSelectedValues[0]
                    : StorageComponent.getValue("lastSelectedWordNum");
        } else if ("lastSelectedPage".equals(key)){
            return StorageComponent.getValue(key) == null
                    ? isEmpty(pageSelectedValues) ? "" : pageSelectedValues[0]
                    : StorageComponent.getValue("lastSelectedPage");
        }
        return "";

    }

    /**
     * 存储
     *
     * @param time 选取的时间值
     */
    private void saveToStorage(String time) {
        StorageComponent.save("lastSelectedMinutes", time);
    }

    private void saveWordToStorage(String word) {
        StorageComponent.save("lastSelectedWordNum", word);
    }
    private void savePageToStorage(String word) {
        StorageComponent.save("lastSelectedPage", word);
    }

    /**
     * 判断数组是否为空
     *
     * @param array 数组
     * @return 是/否
     */
    private boolean isEmpty(String[] array) {
        return array == null || array.length == 0;
    }


    /**
     * 初始化时间下拉框选择
     *
     * @return initValues
     */
    private String[] initTimeSelectValues() {
        return Constant.Settings.TIME_SELECT_ARRAY;
    }

    private String[] initWordSelectValues() {
        return Constant.Settings.WORD_SELECT_ARRAY;
    }
    private String[] initPageSelectValues() {

        LinkedList<String> readLines = FileUtil.readLines(Objects.requireNonNull(showordSetting.class.getClassLoader().getResource("word/CET4.json")), StandardCharsets.UTF_8, new LinkedList<>());
        int page = readLines.size() / Integer.parseInt(readFromStorage("lastSelectedWordNum"));
        int y = readLines.size() % Integer.parseInt(readFromStorage("lastSelectedWordNum"));
        List<String> list = Arrays.asList(Constant.Settings.PAGE_SELECT_ARRAY);
        if (y>0){
            page += 1;
        }
        List<String> arrList = new ArrayList(list);
        for (int i = 0; i <page; i++) {
            arrList.add(i+"");
        }
        return arrList.toArray(new String[arrList.size()+1]);
    }

}
